<template>
  <div class="bg-white rounded-2xl shadow-sm p-8">
    <div class="mb-8">
      <h1 class="text-2xl font-bold text-gray-900 mb-2">通知设置</h1>
      <p class="text-gray-500">自定义您接收通知的方式和内容</p>
    </div>

    <div class="mb-8">
      <div class="flex items-center justify-between mb-6">
        <div>
          <h2 class="text-lg font-semibold text-gray-900 mb-1">接收通知</h2>
          <p class="text-sm text-gray-500">开启后接收所有类型的通知</p>
        </div>
        <label class="relative inline-flex items-center cursor-pointer">
          <input 
            type="checkbox" 
            class="sr-only peer" 
            v-model="settings.notifications_enabled"
            @change="saveSettings"
          >
          <div class="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:border-gray-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
        </label>
      </div>
    </div>

    <div class="mb-8">
      <h2 class="text-lg font-semibold text-gray-900 mb-1">订单通知</h2>
      <p class="text-sm text-gray-500 mb-6">与订单状态相关的通知</p>
      <div class="space-y-4">
        <div class="flex items-start justify-between py-4">
          <div>
            <h3 class="font-medium text-gray-900 mb-1">订单状态变更</h3>
            <p class="text-sm text-gray-500">订单接单、完成、取消等状态变更的通知</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer ml-4">
            <input 
              type="checkbox" 
              class="sr-only peer" 
              v-model="settings.order_status_change"
              @change="saveSettings"
            >
            <div class="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:border-gray-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>
        <div class="flex items-start justify-between py-4">
          <div>
            <h3 class="font-medium text-gray-900 mb-1">快递已送达</h3>
            <p class="text-sm text-gray-500">代拿员已将快递送达指定地点的通知</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer ml-4">
            <input 
              type="checkbox" 
              class="sr-only peer" 
              v-model="settings.order_delivered"
              @change="saveSettings"
            >
            <div class="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:border-gray-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>
        <div class="flex items-start justify-between py-4">
          <div>
            <h3 class="font-medium text-gray-900 mb-1">待支付提醒</h3>
            <p class="text-sm text-gray-500">订单待支付时的支付提醒</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer ml-4">
            <input 
              type="checkbox" 
              class="sr-only peer" 
              v-model="settings.payment_reminder"
              @change="saveSettings"
            >
            <div class="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:border-gray-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>
      </div>
    </div>

    <div class="mb-8">
      <h2 class="text-lg font-semibold text-gray-900 mb-1">系统通知</h2>
      <p class="text-sm text-gray-500 mb-6">平台相关的系统通知</p>
      <div class="space-y-4">
        <div class="flex items-start justify-between py-4">
          <div>
            <h3 class="font-medium text-gray-900 mb-1">账户安全提醒</h3>
            <p class="text-sm text-gray-500">账户异常登录、信息变更等安全提醒</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer ml-4">
            <input 
              type="checkbox" 
              class="sr-only peer" 
              v-model="settings.account_security"
              @change="saveSettings"
            >
            <div class="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:border-gray-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>
        <div class="flex items-start justify-between py-4">
          <div>
            <h3 class="font-medium text-gray-900 mb-1">版本更新提醒</h3>
            <p class="text-sm text-gray-500">平台有新版本发布时的通知</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer ml-4">
            <input 
              type="checkbox" 
              class="sr-only peer" 
              v-model="settings.version_update"
              @change="saveSettings"
            >
            <div class="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:border-gray-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>
      </div>
    </div>

    <div class="mb-8">
      <h2 class="text-lg font-semibold text-gray-900 mb-1">营销通知</h2>
      <p class="text-sm text-gray-500 mb-6">优惠活动、新功能上线等营销类通知</p>
      <div class="space-y-4">
        <div class="flex items-start justify-between py-4">
          <div>
            <h3 class="font-medium text-gray-900 mb-1">优惠活动通知</h3>
            <p class="text-sm text-gray-500">平台优惠活动、折扣信息等通知</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer ml-4">
            <input 
              type="checkbox" 
              class="sr-only peer" 
              v-model="settings.promotions"
              @change="saveSettings"
            >
            <div class="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:border-gray-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>
        <div class="flex items-start justify-between py-4">
          <div>
            <h3 class="font-medium text-gray-900 mb-1">新功能上线</h3>
            <p class="text-sm text-gray-500">平台新功能上线通知</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer ml-4">
            <input 
              type="checkbox" 
              class="sr-only peer" 
              v-model="settings.new_features"
              @change="saveSettings"
            >
            <div class="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:border-gray-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>
      </div>
    </div>

    <div>
      <h2 class="text-lg font-semibold text-gray-900 mb-1">通知方式</h2>
      <p class="text-sm text-gray-500 mb-6">选择接收通知的方式</p>
      <div class="space-y-4">
        <label class="flex items-start cursor-pointer">
          <input 
            type="radio" 
            name="notification-method" 
            value="app"
            v-model="settings.notification_method"
            @change="saveSettings"
            class="mt-1 w-5 h-5 text-blue-600 border-gray-300 focus:ring-blue-500"
          >
          <div class="ml-3">
            <h3 class="font-medium text-gray-900">应用内通知</h3>
            <p class="text-sm text-gray-500">在应用内接收通知消息</p>
          </div>
        </label>
        <label class="flex items-start cursor-pointer">
          <input 
            type="radio" 
            name="notification-method" 
            value="sms"
            v-model="settings.notification_method"
            @change="saveSettings"
            class="mt-1 w-5 h-5 text-blue-600 border-gray-300 focus:ring-blue-500"
          >
          <div class="ml-3">
            <h3 class="font-medium text-gray-900">短信通知</h3>
            <p class="text-sm text-gray-500">通过短信接收重要通知</p>
          </div>
        </label>
        <label class="flex items-start cursor-pointer">
          <input 
            type="radio" 
            name="notification-method" 
            value="email"
            v-model="settings.notification_method"
            @change="saveSettings"
            class="mt-1 w-5 h-5 text-blue-600 border-gray-300 focus:ring-blue-500"
          >
          <div class="ml-3">
            <h3 class="font-medium text-gray-900">邮件通知</h3>
            <p class="text-sm text-gray-500">通过邮箱接收通知</p>
          </div>
        </label>
      </div>
    </div>

    <div v-if="saveStatus" class="mt-6 p-4 rounded-lg" :class="saveStatus === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'">
      {{ saveStatus === 'success' ? '✅ 设置已保存' : '❌ 保存失败，请重试' }}
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'OrderNotify',
  data() {
    return {
      settings: {
        notifications_enabled: true,
        order_status_change: true,
        order_delivered: true,
        payment_reminder: true,
        account_security: true,
        version_update: false,
        promotions: false,
        new_features: false,
        notification_method: 'app'
      },
      saveStatus: '',
      saveTimer: null
    }
  },
  mounted() {
    this.loadSettings()
  },
  methods: {
    async loadSettings() {
      const userId = localStorage.getItem('userId')
      if (!userId) {
        ElMessage.warning('请先登录')
        this.$router.push('/login')
        return
      }

      try {
        const response = await fetch(`/api/users/${userId}/notification-settings`)
        const result = await response.json()
        
        if (result.success && result.data) {
          // 转换数据库的0/1为布尔值
          this.settings = {
            notifications_enabled: result.data.notifications_enabled === 1 || result.data.notifications_enabled === true,
            order_status_change: result.data.order_status_change === 1 || result.data.order_status_change === true,
            order_delivered: result.data.order_delivered === 1 || result.data.order_delivered === true,
            payment_reminder: result.data.payment_reminder === 1 || result.data.payment_reminder === true,
            account_security: result.data.account_security === 1 || result.data.account_security === true,
            version_update: result.data.version_update === 1 || result.data.version_update === true,
            promotions: result.data.promotions === 1 || result.data.promotions === true,
            new_features: result.data.new_features === 1 || result.data.new_features === true,
            notification_method: result.data.notification_method || 'app'
          }
        }
      } catch (error) {
        console.error('加载通知设置失败:', error)
      }
    },
    async saveSettings() {
      const userId = localStorage.getItem('userId')
      if (!userId) return

      // 清除之前的定时器（防抖）
      if (this.saveTimer) {
        clearTimeout(this.saveTimer)
      }

      // 延迟500ms保存，避免频繁请求
      this.saveTimer = setTimeout(async () => {
        try {
          const response = await fetch(`/api/users/${userId}/notification-settings`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              notifications_enabled: this.settings.notifications_enabled ? 1 : 0,
              order_status_change: this.settings.order_status_change ? 1 : 0,
              order_delivered: this.settings.order_delivered ? 1 : 0,
              payment_reminder: this.settings.payment_reminder ? 1 : 0,
              account_security: this.settings.account_security ? 1 : 0,
              version_update: this.settings.version_update ? 1 : 0,
              promotions: this.settings.promotions ? 1 : 0,
              new_features: this.settings.new_features ? 1 : 0,
              notification_method: this.settings.notification_method
            })
          })

          const result = await response.json()

          if (result.success) {
            this.saveStatus = 'success'
            setTimeout(() => {
              this.saveStatus = ''
            }, 2000)
          } else {
            this.saveStatus = 'error'
            setTimeout(() => {
              this.saveStatus = ''
            }, 3000)
          }
        } catch (error) {
          console.error('保存通知设置失败:', error)
          this.saveStatus = 'error'
          setTimeout(() => {
            this.saveStatus = ''
          }, 3000)
        }
      }, 500)
    }
  },
  beforeUnmount() {
    if (this.saveTimer) {
      clearTimeout(this.saveTimer)
    }
  }
}
</script>


